package com.itbaizhan.shopping_admin_service.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itbaizhan.shopping_admin_service.mapper.AdminMapper;
import com.itbaizhan.shopping_common.pojo.Admin;
import com.itbaizhan.shopping_common.pojo.Permission;
import com.itbaizhan.shopping_common.pojo.Role;
import com.itbaizhan.shopping_common.service.AdminService;
import io.netty.util.internal.StringUtil;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author spf
 * @date 2023/12/13
 * @time 12:53
 */

/**
 * 管理员服务实现类
 */
@Service
@Component
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public void add(Admin admin) {
        adminMapper.insert(admin);
    }

    @Override
    public void update(Admin admin) {
        if(StringUtil.isNullOrEmpty(admin.getPassword())){
            String password = adminMapper.selectById(admin.getAid()).getPassword();
            admin.setPassword(password);
        }
        adminMapper.updateById(admin);
    }

    @Override
    public void delete(Long id) {
        // 先删除管理员有的角色
        adminMapper.deleteAllRoleToAdmin(id);
        // 再删除管理员
        adminMapper.deleteById(id);
    }

    @Override
    public Admin findById(Long id) {
        return adminMapper.findById(id);
    }

    @Override
    public Page<Admin> search(int page, int size) {
        return adminMapper.selectPage(new Page<>(page, size), null);
    }

    @Override
    public void updateRoleToAdmin(Long aid, Long[] rids) {
        // 删除管理员的角色
        adminMapper.deleteAllRoleToAdmin(aid);
        // 新增管理员角色
        for (Long rid : rids) {
            adminMapper.addRoleToAdmin(aid, rid);
        }
    }

    @Override
    public Admin findByUsername(String username) {
        QueryWrapper<Admin> wrapper = new QueryWrapper();
        wrapper.eq("username", username);
        return adminMapper.selectOne(wrapper);
    }

    @Override
    public List<Permission> findAllPermissionByUsername(String username) {
        return adminMapper.findAllPermissionByUsername(username);
    }
}
